package com.listeningframework.boot.codegen.database;

import com.listeningframework.boot.codegen.constants.JdbcTypeMapper;
import com.listeningframework.boot.codegen.context.TableMetaData;
import com.listeningframework.boot.codegen.utils.CodeGenUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * MySql Meta Loader
 */
public class MySqlMetaLoader extends MetaLoader {

    @Override
    protected String getMetaSQL(String table) {
        return "show full columns from " + table + ";";
    }

    @Override
    protected List<TableMetaData> getTableMetaData(ResultSet rs) throws SQLException {
        List<TableMetaData> resultList = new ArrayList<>();
        while (rs.next()) {
            String fieldName = rs.getString("Field");
            String fieldType = CodeGenUtils.treatColumnType(rs.getString("Type"));
            String fieldComment = rs.getString("Comment");

            TableMetaData metaData = new TableMetaData();
            metaData.setColumnName(fieldName);
            metaData.setColumnType(fieldType);
            metaData.setComment(fieldComment);
            metaData.setJavaName(CodeGenUtils.columnFieldToJava(fieldName));
            metaData.setJavaTypeClass(JdbcTypeMapper.getType(fieldType));
            resultList.add(metaData);
        }
        return resultList;
    }

}
